import {
  sample,
  createEvent,
  createStore,
  createEffect,
} from 'effector';

import { resetStore } from 'store';
import {
  onSetSensorData,
  onSetSensorCrossCounts,
  onSetSensorSerialNumber,
} from './utils';

import {
  Sensor,
  SensorDataSet,
  SensorsCrossCounts,
  IncomingParserResult,
  SetSensorsCrossCounts,
} from '../types';

// Effect
export const startDataSaver = createEffect(
  (data: IncomingParserResult) => data
);

// Events
export const setSensorSerialNumber = createEvent<SensorDataSet>();
export const setSensorCrossCount = createEvent<SetSensorsCrossCounts>();
export const setSensorData = createEvent<SensorDataSet>();

// Store
export const $sensors = createStore<Sensor[]>([])
  .on(setSensorSerialNumber, onSetSensorSerialNumber)
  .on(setSensorData, onSetSensorData)
  .reset(resetStore);

export const $sensorsCrossCount = createStore<SensorsCrossCounts>({})
  .on(setSensorCrossCount, onSetSensorCrossCounts)
  .reset(resetStore);

sample({
  source: startDataSaver.doneData,
  filter: (data: IncomingParserResult) => data.cmdCode === 253, // Тревога
  target: setSensorData,
});
